#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-07-14 19:29:59
    @email:332904234@qq.com
    @version:1.0
    @fileName:book.py
    @describe:关于图书的视图分发
"""

from django.shortcuts import render, redirect
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.http import JsonResponse
from django.views import View
import json
from book.models import BookModel, TagModel, AuthorModel


class IndexView(View):
    """
    显示图书页面
    """

    @method_decorator(login_required)
    def get(self, request, *args, **kwargs):
        """
        获取图书列表
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        all_book = BookModel.objects.all().order_by('-create_at')
        all_tag = TagModel.objects.all()
        all_author = AuthorModel.objects.all()
        return render(request, 'index.html', locals())

    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        """
        新增图书
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        book_name = request.POST.get('name', None)
        price = request.POST.get('price', None)
        tags = request.POST.getlist('tag', [])
        author = request.POST.get('author', None)
        # 新增数据
        book_result = BookModel.objects.create(name=book_name, price=price, author_id=author)
        # 多对多的添加数据
        book_result.tags.add(*tags)
        return self.get(request)

    @method_decorator(login_required)
    def delete(self, request, *args, **kwargs):
        """
        删除图书
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        book_id = json.loads(request.body).get('id', None)
        if book_id:
            res = BookModel.objects.filter(pk=book_id).delete()
            if res:
                return JsonResponse({'code': 0, 'message': '成功'})
        return JsonResponse({'code': 1, 'message': '失败'})


@login_required
def bookById(request, *args, **kwargs):
    id = kwargs.get('id', None)
    if id:
        book = BookModel.objects.filter(pk=id)
        json_data = serializers.serialize('json', book)
        return JsonResponse({'code': 0, 'message': '成功', 'data': json.loads(json_data, encoding='utf-8')})
    return JsonResponse({'code': 1, 'message': '失败'})


class BookView(View):
    """
    主页数据加载
    """

    @method_decorator(login_required)
    def get(self, request, *args, **kwargs):
        all_book = BookModel.objects.all().order_by('-create_at')
        json_data = serializers.serialize('json', all_book)
        return JsonResponse({'code': 0, 'message': '成功', 'data': json.loads(json_data, encoding='utf-8')}, safe=False)

    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        """
        修改数据
        :param request:
        :return:
        """
        id = json.loads(request.body).get('id', None)
        if id:
            res = BookModel.objects.get(pk=id)
            print(res)
            tag = res.tags.all().values('id')
            print(tag)
            return JsonResponse({'code': 0, 'message': '成功',
                                 'data': {'bookId': res.id, 'name': res.name, 'price': res.price,
                                          'author': res.author.name, 'author_id': res.author.id,
                                          'tag': list(i['id'] for i in tag)}})

    @method_decorator(login_required)
    def delete(self, request, *args, **kwargs):
        """
        根据id删除数据
        :param request:
        :return:
        """
        id = json.loads(request.body).get('id', None)
        if id:
            res = BookModel.objects.get(pk=id).delete()
            if res:
                return JsonResponse({'code': 0, 'message': '成功'})
            return JsonResponse({'code': 1, 'message': '失败'})

    @method_decorator(login_required)
    def put(self, request, *args, **kwargs):
        """
        修改数据
        :param request:
        :return:
        """
        data = json.loads(request.body)
        bookId = data.get('id', None)
        author = AuthorModel.objects.get(pk=data.get('author', None))
        name = data.get('name', None)
        price = data.get('price', None)
        res = BookModel.objects.filter(id=bookId)
        res.update(name=name, price=price, author=author)
        print(data.get('tags', None))
        # res.first().tags.set(*data.get('tags', None))
        if res:
            return JsonResponse({'code': 0, 'message': '成功'})
        return JsonResponse({'code': 1, 'message': '失败'})
